library(ggplot2)
library(tidyr)
library(tidyverse)
library(estimatr)
library(coefplot)
library(patchwork)

# Figure 6: 25% to 75% Change in Support (based on ECDF)

setwd("/Users/dmin/Dropbox/Replication_Data/Paper_3/")

Dat <- read.csv("Paper_3_Data_Clean.csv", stringsAsFactors = FALSE)

x =seq(0, 100, by = 0.5)

my_ecdf <- 
  . %>% 
  split(.$NuclearTheory_fac) %>% 
  map(~ecdf(.$outcome_custom)(x)) %>% 
  data.frame() %>% 
  mutate(x = x) %>% 
  pivot_longer(-x) %>% 
  mutate(
    NuclearTheory_fac = name,
    outcome_custom = value
  )


gg_df <- 
  Dat %>% my_ecdf()

gg_df_1 <- 
  gg_df %>% 
  filter(x == 25) %>% 
  mutate(valuelow = value)

gg_df_2 <- 
  gg_df %>% 
  filter(x == 75) %>% 
  mutate(valuehigh = value)

gg <- full_join(gg_df_1, gg_df_2, by = "name")

gg_2 <- 
  gg %>% 
  mutate(diff = valuehigh-valuelow,
         diff = round(diff,2),
         pct = valuehigh/valuelow - 1,
         pct = 100*pct,
         pct2 = round(pct, 0),
         avg = .5*(valuehigh+valuelow),
         term_label =
           factor(
             name,
             levels = c(
               "Never.Evers",
               "Existential.Deterrence",
               "Offense..Defense",
               "Utilitarian"),
             labels = c(
               "Never-\nEvers",
               "Deterrence",
               "Offense/\nDefense",
               "Utilitarian"
             )
           ))

gg_2$pct2 <- paste(gg_2$pct2, "%", sep="")

g <- ggplot(data=gg_2, aes(x=term_label, color=term_label)) +
  geom_point(aes(y = valuelow)) +
  geom_point(aes(y = valuehigh)) +
  geom_linerange(aes(ymin = valuelow, ymax = valuehigh)) +
  geom_label(aes(y=(avg), label=pct2)) +
  geom_text(aes(y=valuelow-.02, label=round(valuelow,2)))+
  geom_text(aes(y=valuehigh+.02, label=round(valuehigh,2)))+
  theme_bw() + 
  theme(legend.position = "none") +
  xlab("Preferred Theory") + ylab("Change in Support from 25% to 75% Chance of Success") +
  coord_cartesian(ylim=c(0,1)) +
  scale_color_manual(values = c(
    "green3",
    "yellow3",
    "orange3",
    "red3"))

g

ggsave("Image_6.png", plot=g, width=2000, height=2000, units=c("px"))

